from fastapi import FastAPI
from pydantic import HttpUrl
from paddleocr import PaddleOCR
import fitz  # PyMuPDF
import requests
import tempfile
import os

app = FastAPI()
ocr = PaddleOCR(use_angle_cls=True, lang="ch", use_gpu=True)

@app.get("/ocr")
def extract_text_from_pdf(url: HttpUrl):
    with tempfile.TemporaryDirectory() as tmpdir:
        local_path = os.path.join(tmpdir, "doc.pdf")
        with open(local_path, "wb") as f:
            f.write(requests.get(str(url)).content)

        doc = fitz.open(local_path)
        all_text = ""
        for page in doc:
            pix = page.get_pixmap(dpi=200)
            img_path = os.path.join(tmpdir, f"page_{page.number}.png")
            pix.save(img_path)
            result = ocr.ocr(img_path, cls=True)
            for line in result:
                for word in line:
                    all_text += word[1][0] + "\n"
        return {"text": all_text.strip()}
